//
//  YiHomeCtrl.swift
//  yiplayer
//
//  Created by wkun on 2024/6/5.
//

import UIKit
import HXPhotoPicker
import AVKit
import SMBClient

class YiHomeCtrl: BLVideoPlayer {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.nodataView.moreBtn.addTarget(self, action: #selector(handleMenuBtn), for: .touchUpInside)
        self.controlView.moreBtn.addTarget(self, action: #selector(handleMenuBtn), for: .touchUpInside)
    }

    // MARK: - TouchEvents
    @objc func handleMenuBtn() {
        YiLeftMenuView.showLeftMenuView(self, width: self.view.frame.width, height: self.view.frame.height)
    }
    
    func handleMenuItem(index: Int) {
        let i = index
        if i == 0 {
            // 打开相册
            var config = PickerConfiguration.default
            config.previewView.bottomView.isHiddenEditButton = true
            config.selectOptions = [.video]
            config.selectMode = .single
            config.videoSelectionTapAction = .quickSelect
            
            Photo.picker(
                config
            ) { result, pickerController in
                // 选择完成的回调
                // result 选择结果
                //  .photoAssets 当前选择的数据
                //  .isOriginal 是否选中了原图
                // photoPickerController 对应的照片选择控制器
                
//                let images: [UIImage] = try await result.objects()
//                let urls: [URL] = try await result.objects()
                
//                print(urls)
                result.getURLs { urls in
                    print(urls)
                    if urls.count > 0 {
                        self.playVideo(url: urls.first!)
                    }
                }
            } cancel: { pickerController in
                // 取消的回调
                // photoPickerController 对应的照片选择控制器
            }
        }
        
        //文件
        else if i == 1 {
            self.openFile()
        }
        
        //网络
        else if i == 2 {
            print("开始搜索smb")
            self.searchSmbServer()
        }
    }
    
    func avplay(url: URL) {
        // 创建一个AVPlayer实例
        let player1 = AVPlayer(url: url)
         
        // 创建一个AVPlayerViewController实例并设置player
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player1
         
        // 展示AVPlayerViewController
        self.present(playerViewController, animated: true) {
           playerViewController.player?.play() // 在视图控制器呈现后播放视频
        }
    }
    
    // MARK: - qi
    func playVideo(url: URL) {
        
        let fn = url.lastPathComponent
        if currCtrl() == self.player {
            self.player.stop()
            self.player.play(withURL: url, videoTitle: fn)
        }else {
            player.modalPresentationStyle = .overCurrentContext
            self.present(player, animated: true) {
//                self.player.play(withURL: url, videoTitle: fn)
            }
        }
    }
    
    func currCtrl() -> UIViewController {
        if let c = self.presentedViewController as? BLVideoPlayer {
            return c
        }
        return self
    }

    
    // MARK: - SetupUI
    func setupUI() {
        self.view.backgroundColor = .black
        let logoView = ImageView.img("logo60").pin(.wh(60, 60))
        let textL = Label.font("30").color(ColorF)
        textL.text = "Please add media files"
        VStack(NERSpring, logoView,40,textL,NERSpring).embedIn(self.view).align(.center)
        
        let ig = UIImage.init(named: "list_w")// "home_list")
        let moreBtn = Button.pin(.wh(50, 50))
        moreBtn.img(ig).imageView?.pin(.wh(26, 24))
        moreBtn.setImage(ig?.withTintColor(ColorMain), for: .highlighted)
        moreBtn.addTo(self.view).makeCons { make in
            make.top.equal(10)
            make.right.equal(-10)
        }
        moreBtn.addTarget(self, action: #selector(handleRightMenu), for: .touchUpInside)
        
        self.player.controlView.moreBtn.addTarget(self, action: #selector(handleRightMenuA), for: .touchUpInside)
    }
    
    @objc func handleRightMenuA() {
        YiLeftMenuView.showLeftMenuView(self.player, width: self.view.frame.width, height: self.view.frame.height)
    }
}

// MARK: - 导入系统文件App内的文件
extension YiHomeCtrl: UIDocumentPickerDelegate{
    ///调用系统api，打开FilePicker对话窗
    func openFile(){
        
        if #available(iOS 14.0, *) {
            
            //只打开视频
            if let ty = UTType("public.movie") {
                let controller = UIDocumentPickerViewController(forOpeningContentTypes: [ty])
                controller.shouldShowFileExtensions = true
                controller.delegate = self
                self.currCtrl().present(controller, animated: true)
            }
            
        } else {
            ///此处的字符串，可以查看iOS14中枚举注释中的UIT.
            ///如：
            /**
                An Adobe PDF document.
        
                **UTI:** com.adobe.pdf
        
                **conforms to:** public.data, public.composite-content

                public static var pdf: UTType { get }
            */
      
            let controller = UIDocumentPickerViewController(documentTypes: ["public.content"], in: .import)
            controller.delegate = self
            controller.allowsMultipleSelection = false
            self.currCtrl().present(controller, animated: true)
        }
    }
    
    // UIDocumentPickerDelegate methods
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        // 用户取消了文件选择
        print("取消文件选择")
    }

    ///实现UIDocumentPickerDelegate代理
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        ///读取文件之前需要先获取读取文件的授权
        if let url = urls.first{
            
            let isSecuredURL = url.startAccessingSecurityScopedResource()
            
            defer{
                ///释放权限.
                ///
                ///若需要鉴权，则停止鉴权，否则忽略
                if isSecuredURL {
//                    url.stopAccessingSecurityScopedResource()
                }
            }
            self.startMaunalRecory(ul: url)
        }
    }
    
    func startMaunalRecory(ul: URL) {
        
        self.playVideo(url: ul)
        
        ///拷贝文件到当前目录
//        if let toUrl = fileDir?.appendFilePathComponent(ul.lastPathComponent) {
//            do {
//                try FileManager.default.copyItem(at: ul, to: toUrl)
//                self.loadFileData()
//            } catch {
//                
//            }
//        }
    }
}


//smb访问
extension YiHomeCtrl {
    
//    [[SMBDiscovery sharedInstance] stopDiscovery];
    
    func searchSmbServer() {
        SMBDiscovery.sharedInstance()?.start(of: .any, added: { smbDevice in
            print("Device added: %@", smbDevice);
        }, removed: { smbDevice in
            print("Device added: %@", smbDevice);
        })
    }
}
